<?php

namespace app\admin\controller;

use app\common\AdminController;
use app\admin\model\Tool as ToolDB;
use app\admin\validate\Tool as ToolValidate;
class Tool extends AdminController
{
  protected $field = [];
  protected $allowField = ['tool_name','tool_href','tool_intro','tool_logo'];
  protected function initialize()
  {
    $this->model = new ToolDB();
  }

  public function list(array $rule = [], array $field = [], array $association = [], array $hidden = [])
  {
        $rule = [
      "toolName" => [
        "mode" => "like",
        "field" => "tool_name",
      ],
      "toolIntro" => [
        "mode" => "like",
        "field" => "tool_intro",
      ],
      "createTime" => [
        "mode" => "between",
        "field" => "create_time",
      ],
    ];
    $association = [
      'toollabel' => [
        'field' => 'id,label_name,label_val'
      ]
    ];
    return parent::list($rule, $this->field, $association);
  }

  public function add(array $allowField = [], array $association = [], $data = [], $returnId = true)
  {
    $datas = input('post.');

    try {
      Validate(ToolValidate::class)->check($datas);
    } catch (\Throwable $th) {
      // throw $th;
      return error($th->getMessage());
    }
    $allowField = $this->allowField;
    $allowField[] = 'create_time';
    $allowField[] = 'create_by';
    $association = [
      'toollabel' => [
        'save' => $datas['toollabel']
      ]
    ];
    return parent::add($allowField, $association);
    ;
  }

  public function update(array $allowField = [], array $where = [], array $association = [], $data = [])
  {
    $datas = input('post.');

    try {
      Validate(ToolValidate::class)->check($datas);
    } catch (\Throwable $th) {
      // throw $th;
      return error($th->getMessage());
    }
    $allowField = $this->allowField;
    $allowField[] = 'update_time';
    $allowField[] = 'update_by';
    $tool = $this->model->find($datas[ 'id']);
    $currentLabel = $tool->toollabel()->column('id');
    $newLabel = $datas['toollabel'];
    $labelToAdd = array_diff($newLabel, $currentLabel);
    $labelToRemove = array_diff($currentLabel, $newLabel);
    $association = empty($labelToAdd) && empty($labelToRemove) ? [] : [
      'toollabel' => [
        'save' => $labelToAdd,
        'remove' => $labelToRemove
      ]
    ];
    return parent::update($allowField, [], $association);
  }

  public function del($ids, $type = false, $where = [])
  {
    return parent::del($ids);
  }

  public function get($id, array $field = [], array $where = [], array $association = [], array $hidden = [])
  {
    $association = [
      'toollabel' => [
        'field' => 'id,label_name,label_val'
      ]
    ];
    return parent::get($id, $this->field,[],$association);
  }
}
